package rmhc.gui
{
	import com.greensock.TweenLite;
	import com.greensock.TweenMax;
	
	import flash.display.Bitmap;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.geom.Rectangle;
	import flash.net.URLRequest;
	
	import rmhc.RMHCApp;
	
	public class PotatoeDisplay extends MovieClip
	{
		protected var cur:Loader;
		protected var area:Rectangle;
		
		public function PotatoeDisplay( areaWidth:Number , areaHeight:Number )
		{
			super();
			area = new Rectangle( 0 , 0 , areaWidth , areaHeight );
		}
		
		public function setPotatoe( src:String ):void
		{
			remOld();
			
			cur = new Loader();
			//var req:URLRequest = new URLRequest( RMHCApp.getServerUrl() + src );
			var req:URLRequest = new URLRequest( src );
			//cur.contentLoaderInfo.addEventListener(Event.INIT , onCurInit );
			cur.contentLoaderInfo.addEventListener(Event.COMPLETE , onCurComplete );
			cur.load( req );
		}
		protected function onCurComplete( e:Event ):void
		{
			var li:LoaderInfo = e.target as LoaderInfo;
			var lod:Loader = li.loader;
			if ( cur != lod )
			{
				return;
			}
			
			//вычисляем размеры
			if ( cur.width > area.width || cur.height > area.height )
			{
				//вписываем по наибольшей стороне
				var sx:Number = area.width / cur.width;
				var sy:Number = area.height / cur.height;
				var scale:Number = sx < sy ? sx : sy;
				( cur.content as Bitmap ).smoothing = true;
				cur.scaleX = cur.scaleY = scale;
			}
			//центрируем
			cur.y = ( area.height - cur.height ) / 2;
			cur.x = ( area.width - cur.width ) / 5;
			
			cur.alpha = 0;
			addChild( cur );
			TweenLite.to( cur , 0.8 , { alpha : 1 } );
			
			dispatchEvent( new Event( Event.CONNECT ) );
		}
		
		protected function remOld():void
		{
			if ( cur != null )
			{
				var tw:TweenMax = new TweenMax( cur , 0.8 , { alpha : 0 } );
				tw.addEventListener( Event.COMPLETE , onRemOld );
			}
		}
		protected function onRemOld( e:Event ):void
		{
			var tw:TweenMax = e.target as TweenMax;
			var old:Loader = tw.target as Loader;
			old.unload();
			if ( contains( old ) )
			{
				removeChild( old );
			}
		}
	}
}